package com.jhd.fuzhou.view.photo;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;

import androidx.annotation.NonNull;

import com.github.barteksc.pdfviewer.PDFView;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.service.EPrinterService;
import com.jhd.fuzhou.service.PDFService;
import com.jhd.fuzhou.service.PrinterService;
import com.jhd.fuzhou.util.CustomToast;
import com.jhd.fuzhou.util.DocumentPreview;
import com.jhd.fuzhou.util.UploadFile;
import com.jhd.fuzhou.util.UploadSign;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.view.login.BaseActivity;
import com.jhd.fuzhou.vo.SuperviseEnclosureVo;
import com.jhd.fuzhou.vo.SupervisionInspectionPhotoVo;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static com.jhd.fuzhou.view.login.MainActivity.supervisionInspectionVo;

/*照片导出PDF*/
public class PhotoPrintActivity extends BaseActivity {

    @BindView(R.id.pdfView)PDFView pdfView;
    private Context context = PhotoPrintActivity.this;
    private ProgressDialog _dialog;
    @BindView(R.id.btn_print)Button btn_print;
    private PrinterService printerService;
    private EPrinterService ePrinterService;
    private List<SupervisionInspectionPhotoVo> supervisionInspectionPhotoVoList;
    private SupervisionInspectionPhotoVo supervisionInspectionPhotoVo;
    private String supervisionType;
    private int position;
    private boolean handlerIsAlive=true;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_document_preview);
    }

    @Override
    protected void processLogic() {
        application.addDocActivity(this);
        if(UtilHelper.ePrinterType==0){
            printerService = new PrinterService.Builder(this).build();
        }else{
            ePrinterService=new EPrinterService.Builder(this).build();
        }
        supervisionType=getIntent().getStringExtra("supervisionType");
        String s=getIntent().getStringExtra("position");
        position=Integer.valueOf(s);
        supervisionInspectionPhotoVoList=supervisionInspectionVo.getSupervisionInspectionPhotoVoList();
        supervisionInspectionPhotoVo=supervisionInspectionPhotoVoList.get(position);

        handler.sendEmptyMessage(1);
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(isExport()){
                    application.exitDoc();
                }else{
                    onBackPressed();
                }
            }
        });

        findViewById(R.id.tv_finish).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isExport()){
                    application.exitDoc();
                }else{
                    CustomToast.showText(context,"文书还未生成,请稍等",3000,0,0).show();
                }
            }
        });
        _dialog = new ProgressDialog(context);
        _dialog.setMessage("正在生成图片文书,请稍等...");
        _dialog.show();
    }

    private boolean isExport(){
        List<SuperviseEnclosureVo> superviseEnclosureVoList;
        if(supervisionType.equals("专项监督")){
            superviseEnclosureVoList= supervisionInspectionVo.getDocumentAttachmentList();
        }else{
            superviseEnclosureVoList= supervisionInspectionVo.getSuperviseEnclosureVoList();
        }
        if(superviseEnclosureVoList!=null){
            for (SuperviseEnclosureVo superviseEnclosureVo : superviseEnclosureVoList) {
                if(superviseEnclosureVo.getEnclosureName().equals("现场照片证据"+supervisionInspectionPhotoVo.getPhotoNum())){
                    return true;
                }
            }
        }
        return false;
    }

    @OnClick({R.id.btn_download, R.id.btn_print})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_download:
                UploadFile.copyFile(getExternalFilesDir(null).getPath() + "/Download/document.pdf",
                        getExternalFilesDir(null).getPath() + "/Download/"+supervisionType+"/", supervisionInspectionPhotoVo.getPhotoNum() + ".pdf", context);
                break;
            case R.id.btn_print:
                if(UtilHelper.ePrinterType==0) {
                    printerService.executePrint(btn_print);
                }else {
                    ePrinterService.executePrint(btn_print);
                }
                break;
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if(handlerIsAlive){
                if (msg.what == 1) {//判断保存本地签名是否成功
                    File file1 = new File(getExternalFilesDir(null).getPath() + "/Download/4.png");
                    String path=getExternalFilesDir(null).getPath() + "/Download/photo/test.png";
                    String newPath=getExternalFilesDir(null).getPath() + "/Download/photo/"+supervisionInspectionPhotoVo.getPhotoNum()+".png";
                    File file2 = new File(path);
                    if ((supervisionInspectionVo.getSign1() && !file1.exists())||(!file2.exists())) {
                        handler.sendEmptyMessageDelayed(1, 200);
                    } else {
                        if (supervisionInspectionVo.getSign4())
                            UploadSign.uploadSign(application, context, supervisionInspectionVo, 4, "rcjd", file1);
                        //图片不用判断直接上传
                        new Thread(){
                            @Override
                            public void run() {
                                super.run();
                                compressImage(BitmapFactory.decodeFile(path),newPath,100);
                            }
                        }.start();
                        handler.sendEmptyMessageDelayed(2, 500);
                    }
                } else if (msg.what == 2) {//上传签名是否成功
                    if ((supervisionInspectionVo.getSign4() && supervisionInspectionVo.getUpload4() == null)||(supervisionInspectionVo.getUpload5() == null)) {
                        handler.sendEmptyMessageDelayed(2, 200);
                    } else {
                        exportInquiryRecordPDF();
                    }
                } else if (msg.what == 3) {//上传文书和显示
                    File file = new File(getExternalFilesDir(null).getPath() + "/Download/document.pdf");
                    if (_dialog != null) _dialog.cancel();
                    UploadFile.showPDF(pdfView, file, context);
                    supervisionInspectionVo.setUpload5(null);//图片上传时间短，防止下次进入时自动上传上次的图片
                    supervisionInspectionVo.setSupervisionInspectionPhotoVoList(supervisionInspectionPhotoVoList);
                    UploadFile.uploadFile(application, context, supervisionInspectionVo, file, "现场照片证据"+supervisionInspectionPhotoVoList.get(position).getPhotoNum(), "0",supervisionType);
                }
            }
        }
    };

    private void exportInquiryRecordPDF() {
        supervisionInspectionPhotoVo.setPartySignatureUrl(supervisionInspectionVo.getUpload4()!=null?supervisionInspectionVo.getUpload4().getUrl():null);
        supervisionInspectionPhotoVo.setPhotoUrl(supervisionInspectionVo.getUpload5().getUrl());
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
//        Retrofit retrofit = UtilHelper.retrofit(application,"http://106.15.46.65:9004/");//URL的头
        PDFService vs = retrofit.create(PDFService.class);
        RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"), DocumentPreview.exportPhotoPDF(supervisionInspectionPhotoVo,application));
        Call<ResponseBody> jsonForResultCall = vs.exportSupervisionInspectionPhoto(application.getAccessToken(), requestBody);
        jsonForResultCall.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    if (response.code() == 200) {
                        InputStream inputStream = response.body().byteStream();
                        //保存本地
                        writeResponseBodyToDisk(inputStream);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                String msg = "制作文书失败!";
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });

    }

    public void compressImage(Bitmap bitmap, String path, int quality) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = quality;
        while (baos.toByteArray().length / 1024 > 500&&options>=0) { // 循环判断如果压缩后图片是否大于500kb,大于继续压缩
            baos.reset(); // 重置baos即清空baos
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap2 = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        saveBitmapFile(bitmap2,path);
    }
    public void saveBitmapFile(Bitmap bitmap, String filepath) {
        File file = new File(filepath);//将要保存图片的路径
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            UploadSign.uploadPhoto(application, context, supervisionInspectionVo, 5, "rcjd", file);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private void writeResponseBodyToDisk(InputStream inputStream) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                String fileName = "Download/document.pdf";//文件名
                File dir = new File(getExternalFilesDir(null).getPath() + "/Download/");//路径
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File file = new File(getExternalFilesDir(null).getPath() + "/" + fileName);
                try {
                    int index;
                    byte[] bytes = new byte[1024];
                    FileOutputStream outputStream = new FileOutputStream(file);
                    while ((index = inputStream.read(bytes)) != -1) {
                        outputStream.write(bytes, 0, index);
                    }
                    outputStream.flush();
                    outputStream.close();
                    inputStream.close();
                    handler.sendEmptyMessage(3);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handlerIsAlive=false;
    }
}